package com.siyoumi.app.modules.book.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.Book;
import com.siyoumi.app.entity.BookSku;
import com.siyoumi.app.modules.book.service.SvcBook;
import com.siyoumi.app.modules.book.service.SvcBookSku;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/xadmin/book/book__sku__list")
public class book__sku__list
        extends AdminApiController {

    @GetMapping()
    public XReturn index() {
        InputData inputData = InputData.fromRequest();
        String bookId = inputData.input("book_id");
        Book entityBook = SvcBook.getApp().first(bookId);
        if (entityBook == null) {
            return EnumSys.ERR_VAL.getR("预约ID异常");
        }
        setPageTitle(entityBook.getBook_name(), "-预约时间段");

        String[] select = {
                "t_book_sku.*",
        };
        JoinWrapperPlus<BookSku> query = SvcBookSku.getBean().listQuery(inputData);
        query.select(select);

        IPage<BookSku> page = new Page<>(inputData.getPageIndex(), inputData.getPageSize());
        //list
        IPage<Map<String, Object>> pageData = SvcBookSku.getApp().getMaps(page, query);
        List<Map<String, Object>> list = pageData.getRecords();
        long count = pageData.getTotal();

        for (Map<String, Object> data : list) {
            BookSku entity = SvcBookSku.getApp().loadEntity(data);
            data.put("id", entity.getKey());

            //计算截止时间
            LocalDateTime dateTimeEnd = SvcBookSku.getBean().getDateTimeEnd(entity, XDate.toDateString()
                    , entity.getBsku_before_time());
            data.put("time_end", XDate.format(dateTimeEnd, "HH:mm"));
        }

        getR().setData("list", list);
        getR().setData("count", count);


        return getR();
    }

    //删除
    @PostMapping("/del")
    public XReturn del(String[] ids) {
        return SvcBookSku.getBean().delete(List.of(ids));
    }
}
